<?php
include_once('./config/init.php');

//判断是否有登录
AuthLogin();

//获取列表传递过来的id
$id = isset($_GET['id']) ? $_GET['id'] : 0;

//根据id去数据库查询一下是不是真的存在这条记录
$sql = "SELECT * FROM {$pre_}person WHERE id = $id";

$person = find($sql);

//如果没有 就返回列表页
if (!$person) {
    ShowMsg('员工不存在', 'person_list.php');
    exit;
}

//先查询出所有部门的信息
$sql = "SELECT * FROM {$pre_}department";
$deplist = all($sql);

//获取当前编辑员工的所选部门
$depid = isset($person['depid']) ? $person['depid'] : 0;

//根据部门的id 去找职位列表
$sql = "SELECT *FROM {$pre_}job WHERE depid = $depid";
$joblist = all($sql);

//ajax post数据
$action = isset($_POST['action']) ? $_POST['action'] : '';

//如果action == 'check' 我就知道他的请求是 ajax 异步请求过来的
if ($action == "check") {
    $success = [
        'result' => false, //成功 或者 失败
        'msg' => '', //文案信息
    ];

    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';

    //判断是否为空
    if (empty($phone)) {
        $success['result'] = false;
        $success['msg'] = '手机号码不能为空';
    }

    //去查询数据库手机号是否存在
    $sql = "SELECT * FROM {$pre_}person WHERE phone = '$phone' AND id != $id";

    $result = find($sql);

    //如果不为空，就说明手机号存在，不能添加
    if ($result) {
        $success['result'] = false;
        $success['msg'] = '手机号已存在，不能注册';
    } else {
        //不存在，可以注册
        $success['result'] = true;
        $success['msg'] = '可以注册';
    }

    //将信息返回给前端
    //将php的数据转换为json
    echo json_encode($success);
    exit;
}

//如果action == 'emailcheck' 我就知道他的请求是 ajax 异步请求过来的
if ($action == 'emailcheck') {
    $success = [
        'result' => false, //成功  或者  失败
        'msg' => '', //文案信息
    ];

    //邮箱ajax 异步请求
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';

    //判断是否为空
    if (empty($email)) {
        $success['result'] = false;
        $success['msg'] = '邮箱不能为空';
    }

    //去查询数据库邮箱是否存在
    $sql = "SELECT * FROM {$pre_}person WHERE email = '$email' AND id != $id";
    $result = find($sql);

    //如果不为空，就说明邮箱存在，不能添加
    if ($result) {
        $success['result'] = false;
        $success['msg'] = '邮箱已存在,不能注册';
    } else {
        //不存在，可以注册
        $success['result'] = true;
        $success['msg'] = '可以注册';
    }

    //将信息返回给前端
    //将php的数据转换为json
    echo json_encode($success);
    exit;
}

//如果action == 'timecheck' 我们就知道他的请求是 ajax 异步请求过来的
if ($action == 'timecheck') {
    $success = [
        'result' => false, //成功  或者  失败
        'msg' => '', //文案信息
    ];

    $createtime = isset($_POST['createtime']) ? trim($_POST['createtime']) : '';
    $createtime = strtotime(trim($_POST['createtime']));

    //判断是否为空
    if (empty($createtime)) {
        $success['result'] = false;
        $success['msg'] = '入职时间不能为空';
    }

    if ($createtime > time()) {
        $success['result'] = false;
        $success['msg'] = '入职时间不能大于现在时间';
    } else {
        $success['result'] = true;
        $success['msg'] = '';
    }
    echo json_encode($success);
    exit;
}


//如果action == 'DepCheck' 我们就知道他的请求是 ajax 异步请求过来的
if ($action == 'DepCheck') {
    $success = [
        'result' => false, //成功  或者  失败
        'msg' => '', //文案信息
    ];

    //切换部门，ajax 异步请求  更换  职位列表
    $depid = isset($_POST['depid']) ? $_POST['depid'] : 0;

    //查询职位
    $sql = "SELECT * FROM {$pre_}job WHERE depid = $depid";

    $joblist = all($sql);

    if (empty($joblist)) {
        $success['result'] = false;
        $success['msg'] = '该部门下没有职位';
    } else {
        //有职位
        $success['result'] = true;
        $success['msg'] = $joblist;
    }

    //结束这个ajax请求，并返回结果
    echo json_encode($success);
    exit;
}
//判断是否有post表单
if ($_POST) {
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';

    if (empty($phone)) {
        ShowMsg('手机号不能为空');
        exit;
    }

    //判断手机号是否被注册 但是除了自己
    $sql = "SELECT * FROM {$pre_}person WHERE phone = '$phone' AND id != $id";
    $check = find($sql);


    if ($check) {
        ShowMsg('电话号码已存在');
        exit;
    }

    $email = isset($_POST['email']) ? trim($_POST['email']) : '';

    if (empty($email)) {
        ShowMsg('邮箱不能为空');
        exit;
    }

    //判断手机号是否被注册 但是除了自己
    $sql = "SELECT * FROM {$pre_}person WHERE email = '$email' AND id != $id";
    $check = find($sql);


    if ($check) {
        ShowMsg('邮箱已存在');
        exit;
    }

    //不存在就可以注册

    //封装数据
    $data = [
        'nickname' => trim($_POST['nickname']),
        'sex' => trim($_POST['sex']),
        'phone' => $phone,
        'email' => trim($_POST['email']),
        'address' => trim($_POST['address']),
        //标准时间转换为时间戳
        'createtime' => strtotime(trim($_POST['createtime'])),
        'depid' => trim($_POST['depid']),
        'jobid' => trim($_POST['jobid']),
    ];

    if ($data['createtime'] > time()) {
        ShowMsg('入职时间不能大于现在时间');
        exit;
    }

    //判断一下是否有文件上传
    //判断文件是否存在，并且大小是否大于0
    if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
        //查询
        $sql = "SELECT avatar FROM {$pre_}person WHERE id = $id";

        $list = all($sql);

        //可以提取数组中指定的下标元素出来，放到一个新数组里面
        $avatar = array_column($list, 'avatar');

        //将空值过滤掉
        $avatar = array_filter($avatar);

        //将数组中所有的选项都唯一 去除重复选项
        $avatar = array_unique($avatar);

        //如果数组不为空才去删除图片
        if (!empty($avatar)) {
            foreach ($avatar as $item) {
                //删除文件
                @is_file($item) && @unlink($item);
            }
        }

        //avatar
        $result = upload('avatar', './assets/uploads');

        //将上传好的图片路径，插入到数组里面
        $data['avatar'] = $result;
    }

    //执行更新语句
    $affect = update('person', $data, "id = $id");
    if ($affect) {
        ShowMsg('编辑员工成功', 'person_list.php');
        exit;
    } else {
        ShowMsg('编辑员工失败');
        exit;
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('meta.php'); ?>
</head>

<body>
    <?php include_once('header.php'); ?>

    <?php include_once('menu.php'); ?>
    <div class="content">
        <div class="header">
            <h1 class="page-title">编辑员工</h1>
        </div>

        <ul class="breadcrumb">
            <li>
                <a href="index.php">控制台</a>
                <span class="divider">/</span>
            </li>
            <li>
                <a href="person_list.php">员工列表</a>
                <span class="divider">/</span>
            </li>
            <li class="active">编辑员工</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">
                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='person_list.php'">
                        <i class="icon-list"></i>返回员工列表
                    </button>
                </div>

                <!-- 表单 -->
                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form id="person" method="post" enctype="multipart/form-data">
                                <label>昵称</label>
                                <input type="text" name="nickname" class="input-xxlarge" placeholder="请输入昵称" required value="<?php echo $person['nickname']; ?>" />

                                <label>性别</label>
                                <select name="sex" required class="input-xlarge">
                                    <option value="0" <?php echo $person['sex'] == 0 ? 'selected' : ''; ?>>保密</option>
                                    <option value="1" <?php echo $person['sex'] == 1 ? 'selected' : ''; ?>>男</option>
                                    <option value="2" <?php echo $person['sex'] == 2 ? 'selected' : ''; ?>>女</option>
                                </select>

                                <label>手机号</label>
                                <input type="text" name="phone" class="input-xxlarge" placeholder="请输入手机号" required value="<?php echo $person['phone']; ?>" />
                                <span id="notice" style="display:none;"></span>

                                <label>邮箱</label>
                                <input type="email" name="email" class="input-xxlarge" placeholder="请输入邮箱" required value="<?php echo $person['email']; ?>" />
                                <span id="emailnotice" style="display:none;"></span>

                                <label>详细地址</label>
                                <input type="text" name="address" class="input-xxlarge" placeholder="请输入详细地址" required value="<?php echo $person['address']; ?>" />

                                <label>入职时间</label>
                                <input type="date" name="createtime" class="input-xxlarge" placeholder="请选择入职时间" required value="<?php echo date('Y-m-d', $person['createtime']); ?>" />
                                <span id="timenotice" style="display:none;"></span>

                                <label>员工头像</label>
                                <input type="file" name="avatar" class="input-xxlarge" />
                                <!-- 什么情况下显示图片 -->
                                <!-- 不为空 并且 还得要存在 -->
                                <?php if (!empty($person['avatar']) && is_file($person['avatar'])) { ?>
                                    <a href="<?php echo $person['avatar'] ?>" target="_blank">
                                        <img src="<?php echo $person['avatar'] ?>" style="width:100px;height:100px" />
                                    </a>
                                <?php } ?>

                                <label>所属部门</label>
                                <select name="depid" required class="input-xlarge">
                                    <?php foreach ($deplist as $item) { ?>
                                        <option <?php echo $person['depid'] == $item['id'] ? 'selected' : ''; ?> value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></option>
                                    <?php } ?>
                                </select>

                                <label>所属职位</label>
                                <select name="jobid" required class="input-xlarge">
                                    <?php foreach ($joblist as $item) { ?>
                                        <option <?php echo $person['jobid'] == $item['id'] ? 'selected' : ''; ?> value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></option>
                                    <?php } ?>
                                </select>

                                <label></label>
                                <input class="btn btn-primary" type="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <footer>
                    <hr>
                    <p>&copy; 2017 <a href="#" target="_blank">copyright</a></p>
                </footer>
            </div>
        </div>
    </div>
</body>

</html>
<script>
    //表单提交事件
    $("person").submit(function() {
        //获取手机号、邮箱
        var phone = $("input[name=phone]").val()
        var email = $("input[name=email]").val()

        //手机号验证
        var PhoneReg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;

        //判断手机号码正则
        if (!PhoneReg.test(phone)) {
            alert('手机号码填写格式有误')
            return false
        }

        //判断邮箱
        var EmailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

        if (!EmailReg.test(email)) {
            alert('邮箱填写格式有误')
            return false
        }
    })

    //当手机号改变的时候触发
    $("input[name=phone]").change(function() {
        var phone = $(this).val()

        //拿到内容，正则验证
        //手机号验证
        var PhoneReg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;

        //判断手机号码正则
        if (!PhoneReg.test(phone)) {
            alert('手机号码填写格式有误')
            return false
        }

        //发送一个异步请求,到php服务器里面去
        $.ajax({
            //请求类型
            // async: true,  //默认为异步
            type: 'post',
            url: 'person_add.php',
            data: {
                action: 'check',
                phone: phone
            },
            dataType: 'json', //服务器返回类型
            success: function(success) {
                if (success.result) {
                    //可以注册
                    $("#notice").css({
                        display: 'inline',
                        color: 'green'
                    })

                    $("#notice").text(success.msg)
                } else {
                    //不能注册
                    $("#notice").css({
                        display: 'inline',
                        color: 'red'
                    })

                    $("#notice").text(success.msg)
                }
            }
        })
    })

    //当邮箱改变的时候触发
    $("input[name=email]").change(function() {
        var email = $(this).val()

        //判断邮箱正则
        var EmailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

        if (!EmailReg.test(email)) {
            alert('邮箱填写格式有误')
            return false
        }

        //发送异步请求，到php服务器里面去
        $.ajax({
            type: 'post',
            url: "person_add.php",
            data: {
                action: 'emailcheck',
                email: email
            },
            dataType: 'json', //服务器返回类型
            success: function(success) {
                if (success.result) {
                    //可以注册
                    $("#emailnotice").css({
                        display: 'inline',
                        color: 'green'
                    })

                    $("#emailnotice").text(success.msg)
                } else {
                    //不能注册
                    $("#emailnotice").css({
                        display: 'inline',
                        color: 'red'
                    })

                    $("#emailnotice").text(success.msg)
                }
            }
        })
    })

    //当时间改变的时候触发
    $("input[name=createtime]").change(function() {
        var createtime = $(this).val()

        //发送ajax 异步请求
        $.ajax({
            type: 'post',
            data: {
                action: 'timecheck',
                createtime: createtime
            },
            dataType: 'json',
            success: function(success) {
                if (!success.result) {
                    $("#timenotice").css({
                        display: 'inline',
                        color: 'red'
                    })
                    $("#timenotice").text(success.msg)
                } else {
                    $("#timenotice").css({
                        display: 'none'
                    })
                    $("#timenotice").text(success.msg)
                }
            }
        })
    })

    //部门改变的时候触发
    $("select[name=depid]").change(function() {
        //获取部门id
        var depid = $(this).val()

        //发送ajax 异步请求
        $.ajax({
            //async: true, //默认值
            //发送请求
            type: 'post',
            //请求地址
            //不给url地址 就默认提交当前界面
            // url: "person_add.php",
            //发送的数据
            data: {
                action: 'DepCheck',
                depid: depid
            },
            //服务器返回的数据类型
            dataType: 'json',
            //成功的回调函数
            success: function(success) {
                if (success.result) {
                    //有职位

                    //循环遍历，插入到下拉框中
                    var html = '';

                    for (var item of success.msg) {
                        html += `<option value='${item.id}'>${item.name}</option>`
                    }

                    $('select[name=jobid]').html(html)
                } else {
                    //没有职位
                    $('select[name=jobid]').html('')
                }
            }
        })
    })
</script>